<?php

namespace app\ctrl;

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use Yurun\Util\YurunHttp\Co\Batch;
use Yurun\Util\HttpRequest;

/**
 * 批量组号，并返回每条结果
 */
class Spidercheck extends \app\ctrl\BaseController
{

    /**
     * 显示提交域名视图
     */
    public function step1()
    {
        // 输出详情html内容
        $view = new \core\lib\View(VIEWS);
        $url = env('APP_BASEURL') . 'spidercheck/step2';
        return $view->render('spidercheck-1', [
            'v' => time(),
            'url' => $url,

        ]);
    }

    /**
     * 显示提交域名视图
     */
    public function step11()
    {
        // 输出详情html内容
        $view = new \core\lib\View(VIEWS);
        $url = env('APP_BASEURL') . 'spidercheck/step2';
        return $view->render('spidercheck-1', [
            'v' => time(),
            'url' => $url,
        ]);
    }

    /**
     * 显示提交域名视图
     */
    public function step2()
    {
        $params = post();
        $this->validate($params, [
            'domains' => 'require',
        ]);

        // 获取最后的域名
        $temp = array_filter(explode("\n", trim($params['domains'])));
        $domains = [];
        $i = 0;
        foreach ($temp as $item) {
            $domain = trim($item);
            if (!empty($domain) && $domain !== '域名') {
                $domain = str_replace(['https://', 'http://', '/allsitemap.xml', '?allsitemap.xml', '/sxallsitemap.xml', '?sxallsitemap.xml'], '', $domain);
                $i = $i + 1;
                $domains[] = [
                    'index' => $i,
                    'domain' => $domain,
                    'ret' => '',
                    'body' => '',
                ];

            }
        }
        if (empty($domains)) {
            error('域名参数为空', 10000);
        }
        if (count($domains) > 2000) {
            error('域名最多只能2000个', 10000);
        }

        // 输出详情html内容
        $view = new \core\lib\View(VIEWS);
        return $view->render('spidercheck-2', [
            'v' => time(),
            'exporturl' => env('APP_BASEURL') . 'spidercheck/export',
            'domains' => $domains,
            'domain_count' => count($domains),
            'back_url' => env('APP_BASEURL') . 'spidercheck/step1',
            'websocket_url' => env('APP_WEBSOCKET_URL', 'ws://127.0.0.1:9502'),
        ]);
    }

    /**
     * 导出Excel，根据数据md5值获取缓存数据
     */
    public function export()
    {
        $params = post();
        $this->validate($params, [
            'datamd5' => 'require',
        ]);

        // 获取缓存
        $cacheKey = 'spidercheck:' . $params['datamd5'];
        $redis = new \core\lib\Redis();
        $list = $redis->get($cacheKey);
        if (empty($list)) {
            error('数据已过期，请重新提交并导出');
        }

        // 创建一个新的excel文档
        require_once(VENDOR . '/autoload.php');
        $spreadsheet = new Spreadsheet();
        // 获取当前操作sheet的对象
        $worksheet = $spreadsheet->getActiveSheet();
        // 设置当前sheet的标题
        $worksheet->setTitle('爬虫查询明细-' . date('Ymd'));
        // 设置宽度为true,不然太窄了
        $spreadsheet->getActiveSheet()->getColumnDimension('A')->setAutoSize(true);
        $spreadsheet->getActiveSheet()->getColumnDimension('B')->setAutoSize(true);
        $spreadsheet->getActiveSheet()->getColumnDimension('C')->setAutoSize(true);

        //设置第一条的标题
        $worksheet->setCellValue('A1', '域名')->setCellValue('B1', '组名')
            ->setCellValue('C1', '结果');

        // 设置粗体
        $spreadsheet->getActiveSheet()->getStyle('A1:C1')->getFont()->setBold(true);

        // 定义颜色
        $colorQG = '5cb85c'; // 泉港组
        $colorPT = '56c4db'; // 莆田组
        $colorQT = 'f0ad4e'; // 其他组
        $colorError = 'd9534f'; // 失败组

        // 开始赋值
        if ($list['items']) {
            foreach ($list['items'] as $k => $item) {
                $i = $k + 2;
                $worksheet->setCellValue("A{$i}", $item['domain'])
                    ->setCellValue("B{$i}", $item['groupname'])
                    ->setCellValue("C{$i}", $item['res']);
                $spreadsheet->getActiveSheet()->getStyle("A{$i}:C{$i}")->getFont()->getColor()->setRGB($colorError);
            }
            $i = $i + 1;
        }

        // 注意这边文件名不能带中文
        $filename = 'spidercheck-' . date('YmdHi');
        $format = 'xls';

        return downloadExcel($spreadsheet, $filename, $format);
    }
}